import React from 'react';
import {
    getTextPlaceholder,
    setPropsSlots,
} from '@/components/SlForm/helper.ts';
import { FormItemConfig } from '@/types/form';
import { TableSlotsProps } from '@/types/table';
import {FormInstance} from "antd";

type EventHandlers = {
    [key: string]: (options: { value: any; item: any, form?: FormInstance, record: any, event?: any }) => void;
};
type TableComponentProps = {
    item: FormItemConfig;
    initialValues: Record<string, any>;
    handlers?: EventHandlers;
    style?: Record<any, any>;
    slots: any;
    status?: string
};
const getTableComponentProps = ({
    item,
    handlers,
    initialValues,
    style,
    slots,
    status
}: TableComponentProps) => {
    const comStyle = {
        width: '100%',
        ...style,
    };
    const placeholderList = getTextPlaceholder(item);
    const props: any = {
        ...item.componentProps,
        ...(item.options && { options: item.options }),
        style: comStyle,
        ...placeholderList,
    };
    // 插槽处理
    if (slots) {
        setPropsSlots(item, props, slots);
    }
    if (['ButtonGroup'].includes(item.component)) {
        props['row'] = initialValues;
        if (status) {
            props["status"] = initialValues[status];
        }
    }
    if (["Switch"].includes(item.component)) {
        props["defaultValue"] = initialValues[item.field];
    } else {
        props["value"] = initialValues[item.field];
    }

    // 回调事件处理
    Object.entries(props).forEach(([propName, methodKey]) => {
        if (
            typeof methodKey === 'string' &&
            propName.includes('on') &&
            handlers?.[methodKey]
        ) {
            switch (item.component) {
                case 'Input':
                case 'RadioGroup':
                    props[propName] = (
                        e: React.ChangeEvent<HTMLInputElement>,
                    ) => {
                        handlers?.[methodKey]?.({
                            value: e.target.value,
                            item,
                            record: initialValues
                        });
                    };
                    break;
                default:
                    props[propName] = (value: any, event: any) => {
                        handlers?.[methodKey]?.({
                            value,
                            item,
                            record: initialValues,
                            event
                        });
                    };
                    break;
            }
        }
    });
    return props;
};

export { getTableComponentProps };
